//
//  QXNWeChatPay.m
//  Eakay
//
//  Created by mac on 16/1/4.
//  Copyright © 2016年 旗翔新能源发展有限公司. All rights reserved.
//


#import "HYBIPHelper.h"
#import "NSStack.h"
#import "XMLReader.h"
#import "QXNWeChatPay.h"
#import "CommonCrypto/CommonDigest.h"

@implementation QXNWeChatPay

-(NSMutableDictionary *)wechatPayWithBody:(NSString *)body outTradeNo:(NSString *)outTradeNo payFee:(NSString *)payFee notify_url:(NSString *)notify_url
{
    
    //统一下单
    //https://api.mch.weixin.qq.com/pay/unifiedorder
    //第一步，创建URL
    NSURL *url = [NSURL URLWithString:@"https://api.mch.weixin.qq.com/pay/unifiedorder"];
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
    
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    NSAssert(self.appId && self.mchId, @"appId和mchId为必需属性");
    
    //微信平台ID  AppID
    [dic setValue:self.appId forKey:@"appid"];
    //微信商户ID
    [dic setValue:self.mchId forKey:@"mch_id"];
    //随机数
    self.nocStr =[self generateTradeNO];
    [dic setValue:self.nocStr forKey:@"nonce_str"];
    
    [dic setValue:body forKey:@"body"];
    [dic setValue:body forKey:@"detail"];
    [dic setValue:outTradeNo forKey:@"out_trade_no"];
    [dic setValue:payFee forKey:@"total_fee"];
    
    NSString *spbill_create_ip = [HYBIPHelper getIPAddress] ;
    [dic setValue:spbill_create_ip forKey:@"spbill_create_ip"];
    [dic setValue:notify_url forKey:@"notify_url"];
    [dic setValue:@"APP" forKey:@"trade_type"];
    //签名
    [dic setValue:[self getSign:dic] forKey:@"sign"];
    [self newXMLString:dic];
    
    NSData *xmlData =  [[self newXMLString:dic] dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:xmlData];
    //第三步，连接服务器
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    NSError *parseError = nil;
    NSMutableDictionary *xmlDictionary = [[NSMutableDictionary alloc] initWithDictionary:[XMLReader dictionaryForXMLString:str1 error:&parseError]];

    return xmlDictionary;
}

-(NSString *)getSign:(NSMutableDictionary *)dic
{
    NSArray *keys = [dic allKeys];
    NSArray *sortArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableString *temp=[[NSMutableString alloc] initWithString:@""];
    
    for (NSString *str in sortArray) {
        
        NSString *t =[NSString  stringWithFormat: @"%@=%@&",str,[dic objectForKey:str]];
        [temp appendString:t];
    }
    
    //API Key API 签名生成
    [temp appendString:[NSString stringWithFormat:@"key=%@",self.appId]];

    return [[QXNWeChatPay md5:temp] uppercaseString];
}
///产生随机字符串
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRST";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
    
}
- (NSString*) newXMLString:(NSDictionary *)dic {
    NSMutableString *xmlString = [[NSMutableString alloc] init];
    
    NSArray  *keys = [dic allKeys];
    NSString *key  = nil;
    [xmlString appendString:@"<xml>\n"];
    
     for (key in keys) {
         [xmlString appendString:[NSString stringWithFormat:@"<%@>%@</%@>\n",key,[dic objectForKey:key],key]];
     }
    [xmlString appendString:@"</xml>"];
    
    return xmlString;
}

#pragma mark -

+(NSString *)md5:(NSString *)inPutText {
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    NSString *RES = [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                      result[0], result[1], result[2], result[3],
                      result[4], result[5], result[6], result[7],
                      result[8], result[9], result[10], result[11],
                      result[12], result[13], result[14], result[15]
                      ] lowercaseString];
    return [RES uppercaseString];
}

@end
